package com.asset.dispoal.interestFormula.domain.service.commom;

import com.asset.dispoal.interestFormula.domain.db.entity.InterestFormula;
import com.asset.dispoal.interestFormula.domain.db.mapper.InterestFormulaMapper;
import com.asset.dispoal.interestFormula.domain.service.converter.InterestFormulaConverter;
import com.asset.dispoal.interestFormula.dto.InterestFormulaDetailRequest;
import com.asset.dispoal.interestFormula.dto.InterestFormulaRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

/**
 * @author qr
 * @date 2022/3/28$
 */
@Component
public class InterestFormulaUpdateCommand implements BaseCommand<InterestFormulaRequest, Result> {

    @Autowired
    InterestFormulaMapper interestFormulaMapper;

    @Autowired
    BaseIdeable<String> ideable;

    @Override
    public Result execute(InterestFormulaRequest request) {
        if (CollectionUtil.isEmpty(request.getDetailList())) {
            return Result.faild("请先配置利率得详情公式");
        }
        InterestFormula interestFormula = InterestFormulaConverter.INSTANCE.reqToDo(request);
        interestFormulaMapper.update(interestFormula);
        interestFormulaMapper.deleteDetail(interestFormula.getId());
        for (InterestFormulaDetailRequest detailRequest : request.getDetailList()) {
            if (StringUtil.isEmpty(detailRequest.getId())) {
                detailRequest.setFormulaId(interestFormula.getId());
                detailRequest.setId(ideable.generateId());
                interestFormulaMapper.insertDetail(detailRequest);
            } else {
                interestFormulaMapper.insertDetail(detailRequest);
            }

        }
        return Result.ok();
    }
}
